package com.oceansoft.mobile.econsole.modules.weixin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.oceansoft.mobile.econsole.common.constant.ConfigInfo;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.modules.base.entity.ApiPager;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.weixin.entity.LostPerson;
import com.oceansoft.mobile.econsole.modules.weixin.service.ILostPersonService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * ClassName: ILostPersonServiceImpl
 * Desc:
 * Date： 2017/3/29
 * Created：shaom
 */
@Service
public class ILostPersonServiceImpl implements ILostPersonService {

    @Resource
    ConfigInfo configInfo;

    @Override
    public ApiPager<LostPerson> loadByPage(Query query) {
        String res = null;
        int pageNum = query.getPageNum();
        int numPerPage = query.getNumPerPage();
        String keywords = query.getKeywords();

        String url = configInfo.getServiceInterfaceAddress() + "/apphub/lostperson/page?pi=" + pageNum + "&ps=" + numPerPage;
        url = !Strings.isNullOrEmpty(keywords) ? url + "&lostpersonname=" + keywords : url;
        try {
            res = HttpClientUtil.doGet(url);
        } catch (IOException e) {
        }
        JSONObject object = JSON.parseObject(res);
        Preconditions.checkArgument(object.getBooleanValue("succ"), "获取接口数据返回失败");

        JSONObject jsonObject = object.getJSONObject("data");
        int pageSize = jsonObject.getIntValue("pageSize");
        int pageIndex = jsonObject.getIntValue("pageIndex");
        long totalRow = jsonObject.getLongValue("totalRow");
        List<LostPerson> list = JSON.parseArray(jsonObject.getString("list"), LostPerson.class);

        ApiPager pager = new ApiPager(pageSize, pageIndex, totalRow, list);
        return pager;
    }

    @Override
    public Result findLostPersonById(String guid) {

        String url = configInfo.getServiceInterfaceAddress() + "/apphub/lostperson/" + guid;
        String res = null;
        try {
            res = HttpClientUtil.doGet(url);
        } catch (IOException e) {
        }

        JSONObject object = JSON.parseObject(res);
        Preconditions.checkArgument(object.getBooleanValue("succ"), "获取接口数据返回失败");

        LostPerson data = object.getObject("data", LostPerson.class);
        return new Result(Result.SUCC, data);
    }
}
